package webappcontrollers

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"smartcap-api/equappcontrollers"
	"strings"
	"smartcap-api/models"
)

//文件加载
type FileDownloadController struct {
	beego.Controller
}

//func (c *FileDownloadController) FileAllowCross() {
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Origin", "http://localhost:14000")       //允许访问源
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Methods", "POST, GET, PUT, OPTIONS")    //允许post访问
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization") //header的类型
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Max-Age", "1728000")
//	c.Ctx.ResponseWriter.Header().Set("Access-Control-Allow-Credentials", "true")
//	c.Ctx.ResponseWriter.Header().Set("content-type", "application/json") //返回数据格式是json
//}

type File struct {
	Id string `json:"id"`
	Filename string `json:"filename"`
	Filetype string `json:"filetype"`
	Deviceid string `json:"deviceid"`
	Company  string  `json:"company"`
	Coordinate string `json:"coordinate"`
	Uploadtime string `json:"uploadtime"`
}

type FILEJSONS struct {
	//必须的大写开头
	Error_code int `json:"error_code"`
	Total int `json:"total"`
	DATA []File  `json:"data"`
}

//查询所有文件
func (this *FileDownloadController) QueryAllFileInfo() {
	//this.FileAllowCross()
	equappcontrollers.FileLogs.Info("===查询所有文件===")
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	page := this.GetString("page")
	size := this.GetString("size")

	fileDataChan := make(chan string, 100000)
	totalItem := models.ReadFile(fileDataChan,company,page,size)
	filedata := []File{}
	tempdata := File{"","","","","","",""}
	//遍历信道，读取数据
	var i int = 0
	var lenfiledatachan = len(fileDataChan)
	if lenfiledatachan != 0 {
		for item := range fileDataChan{
			itemsegments := strings.Split(item,"and")
			tempdata = File{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5],itemsegments[6]}
			filedata = append(filedata, tempdata)
			if i == (lenfiledatachan - 1) {
				break
			}
			i++
		}
		data := &FILEJSONS{0,totalItem,filedata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		filedata = append(filedata, tempdata)
		data := &FILEJSONS{1, 0, []File{}}
		this.Data["json"] = data
		this.ServeJSON()
	}
}


//文件删除,目前只删除数据库中的文件信息，而不删除文件系统中的文件
func (this *FileDownloadController) DeleteFilebyfilename() {
	equappcontrollers.FileLogs.Info("===文件删除===")
	//this.FileAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	company := GetCompanyfromToken(token)
	//fmt.Println(company)
	body := this.Ctx.Input.RequestBody //这是获取到的json二进制数据
	//fmt.Println(string(body))
	fencearray := Getinfofromarray(string(body))
	//fmt.Println(fencearray)
	type JSONS struct {
		//必须的大写开头
		Error_code int `json:"error_code"`
	}
	o := orm.NewOrm()
	for i := 0; i < len(fencearray); i++{
		_, err := o.Raw("delete from  file_info  where filename = ? and company = ?",fencearray[i],company).Exec()
		if err != nil{
			fmt.Println("删除失败！")
			data := &JSONS{1}
			this.Data["json"] = data
			this.ServeJSON()
		}
	}
	data := &JSONS{0}
	this.Data["json"] = data
	this.ServeJSON()
}


//条件查询文件
func (this *FileDownloadController)Queryfile(){
	equappcontrollers.FileLogs.Info("===条件查询文件===")
	//this.FileAllowCross()
	token := this.Ctx.Request.Header.Get("Authorization")
	starttime := this.GetString("starttime")
	endtime := this.GetString("endtime")
	filetype := this.GetString("filetype")
	page := this.GetString("page")
	size := this.GetString("size")
	deviceid := this.GetString("deviceid")
	jsoninfo := ParseToken(token)
	username := Getusernamefromjsoninfo(jsoninfo)
	company := models.QueryCompanyByUsername(username)
	alarmDataChan := make(chan string, 100000)
	totalItem := models.Queryfilebycondition(alarmDataChan,company,starttime,endtime,filetype,deviceid,page,size)
	//fmt.Println(totalItem)
	alarmdata := []File{}
	tempdata := File{"","","","","","",""}
	//遍历信道，读取数据
	var i int = 0
	var lenalarmchan = len(alarmDataChan)
	if lenalarmchan != 0 {
		for item := range alarmDataChan{
			//fmt.Println("get data from database:",item)
			//m[strconv.Itoa(i)] =item
			itemsegments := strings.Split(item,"and")
			tempdata = File{itemsegments[0],itemsegments[1],itemsegments[2],itemsegments[3],itemsegments[4],itemsegments[5],itemsegments[6]}
			alarmdata = append(alarmdata, tempdata)
			if i == (lenalarmchan - 1) {
				break
			}
			i++
		}
		data := &FILEJSONS{0,totalItem,alarmdata}
		this.Data["json"] = data
		this.ServeJSON()
	}else {
		alarmdata = append(alarmdata, tempdata)
		data := &FILEJSONS{1, totalItem, []File{}}
		this.Data["json"] = data
		this.ServeJSON()
	}
}


//文件下载方法
func (this *FileDownloadController) FileDownload() {
	equappcontrollers.FileLogs.Info("===文件下载===")
	token := this.Ctx.Request.Header.Get("Authorization")
	equappcontrollers.FileLogs.Info(token)
	//company := GetCompanyfromToken(token)
	//equappcontrollers.FileLogs.Info("公司是：",company)
	filename := this.GetString("filename")
	//fmt.Println("filename:", filename)
	filepath := "static/upload/%s"
	path := fmt.Sprintf(filepath, filename)
	//fmt.Println(path)
	//第一个参数是文件的地址，第二个参数是下载显示的文件的名称
	this.Ctx.Output.Download(path)
}
